package textop

import (
	"log"
	"logbeat/internal/globalvar"
	"logbeat/internal/req"
	"strings"

	"go.uber.org/zap"
)

func ListenTextChan() {
	for {
		// tex[0] 是当前索引
		// txt[1] 是日志内容
		txt := <-globalvar.TxtChan
		log.Println(txt)
		url := globalvar.SysConf.ZincsearchServer.Address + "/api/" + txt[0] + "/_doc"
		if err := retry(url, txt[1]); err != nil {
			log.Fatalln("error", zap.Error(err))
			// 	// this.loop(url, txt)
		}
	}
}

func retry(url string, logContent string) error {
	var (
		err error
		num int
	)
	for {
		if num == 3 {
			return err
		}
		bd, status, _err := req.Request("POST", url, strings.NewReader(logContent))
		if _err != nil {
			num += 1
			err = _err
			continue
		}
		if status != 200 {
			log.Fatalln("response_not_200", zap.String("txt", logContent), zap.String("body", bd), zap.Int("status", status))
		}
		return nil
	}
}
